package com.mapbased.sfw.component;

import org.dom4j.Element;

import com.mapbased.sfw.model.LoadContext;
import com.mapbased.sfw.model.RenderContext;
import com.mapbased.sfw.util.Strings;

public abstract class Property <T>{
	final String name;
	final String caption;
	public Property(String name ){
		this.name=name;
		this.caption=name;
	}
	public Property(String name,String caption){
		this.name=name;
		this.caption=caption;
	}
	
	protected abstract T  parse(String val);
	protected   String format(T v){
		return String.valueOf(v);
	}
	public final void parseReq(RenderContext rc,Component com){
		String v=rc.req.param(name);
		if(v!=null){
			com.setProperty(name, this.parse(v));
		}
	}
	
	final public void parseXml(Element ele, LoadContext lc,Component com){
		String s=lc.fetchAttribute(ele, name);
		if(s!=null){
			com.setProperty(name, this.parse(s));
		}
	}
	@SuppressWarnings("unchecked")
	final public void toXml(XmlContext xc,Component com){
		T property = (T)com.getProperty(name);
		xc.sb.append(this.name).append("\"").append(Strings.toXmlAttributeSafe(
				format(	property)
		)).append("\"");
	}
	public static class Str extends Property<String>{

		public Str(String name, String caption) {
			super(name, caption);
		 
		}

		@Override
		protected String parse(String val) {
		 
			return val;
		}
		
	}
	public static class Long extends Property<java.lang.Long>{

		public Long(String name, String caption) {
			super(name, caption);
		 
		}

		@Override
		protected java.lang.Long parse(String val) {
		return java.lang.Long.parseLong(val);
		}
		
	}
	public static class Int extends Property<Integer>{

		public Int(String name, String caption) {
			super(name, caption);
		 
		}

		@Override
		protected Integer parse(String val) {
			 
			return Integer.parseInt(val);
		}
		
	}
	public static class Bool extends Property<Boolean>{

		public Bool(String name, String caption) {
			super(name, caption);
		 }

		@Override
		protected Boolean parse(String val) {

			return Boolean.parseBoolean(val);
 
		}
		
	}
 }
